#include "HttpServer.hpp"
#include "Usage.hpp"
#include "Util.hpp"
#include <memory>
#include <fstream>
#define ROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void HandlaerHttpRequest(int sock)
{
    char buffer[10240];
    ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
    if (s > 0)
    {
        buffer[s] = 0;
        std::cout << buffer << std::endl;
    }
    std::vector<std::string> vlist;
    Util::cutString(buffer, "\r\n", &vlist);
    std::vector<std::string> vblock;
    Util::cutString(vlist[0], " ", &vblock);
    std::string file = vblock[1];
    std::string target = ROOT;
    // if (file == "/")
    // {
    //     file = HOMEPAGE;
    // }
    target += file;
    // std::cout << target << std::endl;
    std::string content;
    std::ifstream in(target);
    if (in.is_open())
    {
        std::string line;
        while (std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }

    // for(auto &iter : vblock)
    // {
    //     std::cout << "------";
    //     std::cout << iter << std::endl;
    // }

    std::string HttpRespone;
    if (content.empty())
    {
        HttpRespone = "HTTP/1.1 301 Moved Permanently\r\n";
        HttpRespone += "Location: https://www.runoob.com/html/html-forms.html";
    }
    else
    {
        HttpRespone = "HTTP/1.1 200 OK\r\n";
        HttpRespone += ("Content-Length: " + std::to_string(content.size()) + "\r\n");
        HttpRespone += ("Content-Type: text/html\r\n");
        HttpRespone += "Set-Cookie: 这是一个cookie\r\n";
    }
    HttpRespone += "\r\n";
    HttpRespone += content;
    send(sock, HttpRespone.c_str(), HttpRespone.size(), 0);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]), HandlaerHttpRequest));
    httpserver->Start();

    return 0;
}